<template>
	<div class="login-container">
		<div class="login-box">
			<h2 class="title">{{ $t('message.title') }}</h2>
			<form @submit.prevent="handleLogin">
				<div class="form-group">
					<input type="text" v-model="state.ruleForm.userName" :placeholder="$t('message.placeholder1')" required />
				</div>
				<div class="form-group">
					<input type="password" v-model="state.ruleForm.password" :placeholder="$t('message.placeholder2')" required />
				</div>

				<button @click="onSignIn" type="submit" class="login-button">登录</button>
			</form>
		</div>
	</div>
</template>

<script setup name="loginAccount">
import { reactive, computed, onMounted } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { ElMessage } from 'element-plus';
import { useI18n } from 'vue-i18n';
import Cookies from 'js-cookie';
import { storeToRefs } from 'pinia';
import { useThemeConfig } from '/@/stores/themeConfig';
import { initFrontEndControlRoutes } from '/@/router/frontEnd';
import { initBackEndControlRoutes } from '/@/router/backEnd';
import { Session } from '/@/utils/storage';
import { formatAxis } from '/@/utils/formatTime';

// 定义变量内容
const { t } = useI18n();
const storesThemeConfig = useThemeConfig();
const { themeConfig } = storeToRefs(storesThemeConfig);
const route = useRoute();
const router = useRouter();
const state = reactive({
	isShowPassword: false,
	ruleForm: {
		userName: 'admin',
		password: '123456',
		code: '1234',
	},
	loading: {
		signIn: false,
	},
});

// 时间获取
const currentTime = computed(() => {
	return formatAxis(new Date());
});

// 登录
const onSignIn = async () => {
	state.loading.signIn = true;
	// 存储 token 到浏览器缓存
	Session.set('token', Math.random().toString(36).substr(0));
	// 模拟数据，对接接口时，记得删除多余代码及对应依赖的引入。用于 `/src/stores/userInfo.ts` 中不同用户登录判断（模拟数据）
	Cookies.set('userName', state.ruleForm.userName);

	if (!themeConfig.value.isRequestRoutes) {
		// 前端控制路由，2、请注意执行顺序
		const isNoPower = await initFrontEndControlRoutes();
		signInSuccess(isNoPower);
	} else {
		// 模拟后端控制路由，isRequestRoutes 为 true，则开启后端控制路由
		// 添加完动态路由，再进行 router 跳转，否则可能报错 No match found for location with path "/"
		const isNoPower = await initBackEndControlRoutes();
		// 执行完 initBackEndControlRoutes，再执行 signInSuccess
		signInSuccess(isNoPower);
	}
};

// 登录成功后的跳转
const signInSuccess = (isNoPower) => {
	if (isNoPower) {
		const promptText = t('message.promptText');
		ElMessage.warning(`${promptText}`);
		Session.clear();
	} else {
		// 初始化登录成功时间问候语
		let currentTimeInfo = currentTime.value;
		// 登录成功，跳到转首页
		// 如果是复制粘贴的路径，非首页/登录页，那么登录成功后重定向到对应的路径中
		if (route.query?.redirect) {
			router.push({
				path: route.query?.redirect,
				query: Object.keys(route.query?.params).length > 0 ? JSON.parse(route.query?.params) : '',
			});
		} else {
			router.push('/smartLargeScreen/mainStationScreenNews');
		}
		// 登录成功提示
		const signInText = t('message.signInText');
		ElMessage.success(`${currentTimeInfo}，${signInText}`);
		// 添加 loading，防止第一次进入界面时出现短暂空白
		// NextLoading.start();
	}
	state.loading.signIn = false;
};

onMounted(() => {});
</script>

<style scoped>
.login-container {
	display: flex;
	justify-content: center;
	align-items: center;
	height: 100vh;
	background: url('../../assets/banner.jpg') no-repeat center/cover;
	background-size: cover;
}

.login-box {
	background-color: white;
	padding: 20px;
	border-radius: 8px;
	box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
	width: 300px;
}

h2 {
	text-align: center;
	margin-bottom: 20px;
}

.form-group {
	margin-bottom: 15px;
}

input[type='text'],
input[type='password'] {
	width: 100%;
	padding: 10px;
	border: 1px solid #ccc;
	border-radius: 4px;
}

.captcha-image {
	width: 100px;
	height: 40px;
	cursor: pointer;
}

.login-button {
	width: 100%;
	padding: 10px;
	background-color: #409eff;
	color: white;
	border: none;
	border-radius: 4px;
	cursor: pointer;
	font-size: 1.2rem;
	font-weight: bold;
}

.login-button:hover {
	background-color: #333;
}
</style>
